const fs = require('fs');
const xlsx = require('xlsx');
const { changeArrayToObject, changeKeyTwo, changeKeyOne } = require('./utils');

// 列出文件名、转换后的文件名以及格式化对象
const fileList = [
  {
    before: 'page1',
    after: 'pageOne',
    changeObj: changeKeyOne,
  },
  {
    before: 'page2',
    after: 'pageTwo',
    changeObj: changeKeyTwo,
  },
  {
    before: 'page3',
    after: 'pageThree',
    changeObj: changeKeyOne,
  },
];

const getExcelData = (props) => {
  const { before, after, changeObj } = props;
  // 读取xlsx文件
  const workbook = xlsx.readFile(process.cwd() + '/node/' + before + '.xlsx');
  // 获取第一个工作表
  const workSheet = workbook.Sheets[workbook.SheetNames[0]];

  // 将工作表转换为JSON

  const jsonData = xlsx.utils.sheet_to_json(workSheet, {
    header: 1,
    defval: '',
  });
  // 将二维数组数据转换成对象数组
  const newData = changeArrayToObject({
    sheetData: jsonData,
    changeObj: changeObj,
  });

  /*
  先清空文件内容再重新写入
  */
  // 清空文件内容
  fs.writeFile(process.cwd() + '/node/' + after + '.json', '', (err) => {
    if (err) {
      console.error('Error clearing file content:', err);
      return;
    }
    // 写入文件内容
    fs.writeFile(
      process.cwd() + '/node/' + after + '.json',
      JSON.stringify(newData),
      (err) => {
        if (err) {
          console.error('Error writing to file:', err);
        } else {
          console.log('File content has been updated successfully!');
        }
      },
    );
  });
};
/*
依次处理page1\page2\page3
*/
fileList.forEach((val) => {
  getExcelData(val);
});

// console.log(newData)
